package com.aboverock.core.shiro.filter;

import com.aboverock.autoconfigure.util.JwtUtil;
import com.aboverock.core.token.JwtToken;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;


/**
 * 
 * @author Rock Wang
 *
 */
public class JwtShiroFilter extends AccessControlFilter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
            httpResponse.setHeader("Access-Control-Allow-Methods", httpRequest.getMethod());
            httpResponse.setHeader("Access-Control-Allow-Headers",
                    httpRequest.getHeader("Access-Control-Request-Headers"));
            httpResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        String token = JwtUtil.getRequestToken((HttpServletRequest) request);
        if (null == token) {
            logger.debug("Data-Smart: request中未包含token");
            return false;
        }

        JwtToken jwtToken = new JwtToken(token);
        Subject subject = getSubject(request, response);
        try {
            subject.login(jwtToken);
        } catch (AuthenticationException e) {
            return false;
        }

        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        logger.info("Data-Smart: JWT验证失败");
        ((HttpServletResponse) response).setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }

}
